<!-- 仓库设置 -->
<script setup lang="ts">
import type { TreeInstance } from 'element-plus';

import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import type { DictApi, WareStock } from '#/api';

import { nextTick, reactive, ref, watch } from 'vue';

import { Switch } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { DictResp, getWareStockTableList, getWareStockTreeSelect } from '#/api';

import { handleWmstockSwitchChange } from '../common/common';
import { useColumns } from './data';

interface Tree {
  [key: string]: any;
}
// 将字典数据添加到数组中
const sys_yes_no = reactive<DictApi.SelectOption[]>([]);

DictResp(['sys_yes_no']).then((res) => {
  if (res.sys_yes_no) {
    sys_yes_no.push(...res.sys_yes_no);
  }
});
// 存储选中行的响应式变量
const selectedRows = ref<any[]>([]);

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      fieldName: 'itemTypeId',
      dependencies: {
        triggerFields: ['itemTypeId'],
        show: false,
      },
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入产品物料编码',
        allowClear: true,
        class: 'mr-5',
      },
      fieldName: 'areaCode',
      label: '产品物料编码',
      labelClass: '  text-[#606266] font-bold',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入产品物料名称',
        allowClear: true,
      },
      fieldName: 'itemName',
      label: '产品物料名称',
      labelClass: '  text-[#606266] font-bold',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入批次号',
        allowClear: true,
      },
      fieldName: 'batchCode',
      label: '批次号',
      labelClass: '  text-[#606266] font-bold',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入仓库名称',
        allowClear: true,
      },
      fieldName: 'warehouseName',
      label: '仓库名称',
      labelClass: '  text-[#606266] font-bold',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入库区名称',
        allowClear: true,
      },
      fieldName: 'locationName',
      label: '库区名称',
      labelClass: '  text-[#606266] font-bold',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入库位编码',
        allowClear: true,
      },
      fieldName: 'areaName',
      label: '库位编码',
      labelClass: '  text-[#606266] font-bold',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: sys_yes_no,
        placeholder: '请选择',
      },
      fieldName: 'frozenFlag',
      label: '是否冻结',
      labelClass: '  text-[#606266] font-bold',
    },
  ],

  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '搜索',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

const gridOptions: VxeGridProps<WareStock.Row> = {
  columns: useColumns(),
  checkboxConfig: {
    highlight: true,
  },
  autoResize: false,
  // 虚拟滚动配置项
  virtualYConfig: { enabled: true },
  keepSource: true,
  pagerConfig: {
    enabled: true,
    layouts: [
      'Total',
      'Sizes',
      'PrevJump',
      'PrevPage',
      'Number',
      'NextPage',
      'NextJump',
      'FullJump',
    ],
    align: 'right',
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        formValues.itemTypeId = treeRef.value?.getCurrentKey();
        const res = await getWareStockTableList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        return { items: res.rows, total: res.total };
      },
    },
  },
  tooltipConfig: {
    // 是否开启全局文本提示
    showAll: false,
  },
  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    custom: true,
    zoom: true,
    refresh: { code: 'query' },
    buttons: [
      {
        name: '导出',
        code: 'export',
        status: 'primary',
        icon: 'vxe-icon-download',
      },
    ],
  },
};

const gridEvents: VxeGridListeners = {
  checkboxChange() {
    selectedRows.value = gridApi.grid.getCheckboxRecords();
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

/* 树形控件 */
const filterText = ref('');
const treeRef = ref<TreeInstance>();

const defaultProps = {
  children: 'children',
  label: 'label',
};
const data = ref<Tree[]>([]);
getWareStockTreeSelect().then((res) => {
  data.value = res.data;
  nextTick(() => {
    treeRef.value?.filter('');
  });
});

watch(filterText, (val) => {
  // eslint-disable-next-line unicorn/no-array-callback-reference
  treeRef.value!.filter(val);
});

const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.label.includes(value);
};

function handleNodeClick(data: Tree) {
  gridApi.formApi.getValues().then((res) => {
    res.itemTypeId = data.id;
    gridApi.query(res);
  });
}
</script>

<template>
  <div class="vp-raw flex w-full gap-2">
    <div class="ml-2 mt-2 w-[15%]">
      <el-input
        v-model="filterText"
        class="mb-2"
        placeholder="请输入分类名称"
      />
      <el-tree
        ref="treeRef"
        style="height: 100%"
        class="filter-tree"
        :data="data"
        :props="defaultProps"
        default-expand-all
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
        :expand-on-click-node="false"
        node-key="id"
        highlight-current
      />
    </div>
    <div class="mt-2 w-[85%]">
      <Grid>
        <template #frozenFlag="{ row }">
          <span
            class="mr-[10px]"
            :class="[{ 'blue-text': row.frozenFlag === 'N' }]"
          >
            否
          </span>
          <Switch
            :checked="row.frozenFlag === 'N' ? false : true"
            @update:checked="
              (val) => handleWmstockSwitchChange(row, val as number)
            "
            :aria-label="null"
          />
          <span
            class="ml-[10px]"
            :class="[
              {
                'blue-text': row.frozenFlag === 'Y',
              },
            ]"
          >
            是
          </span>
        </template>
      </Grid>
    </div>
  </div>
</template>

<style scoped>
.blue-text {
  color: #1890ff;
}
</style>
